package com.jiunuan.live.core.server.service.impl;

import com.alibaba.fastjson2.JSON;
import com.jiunuan.live.core.server.common.ChannelHandlerContextCache;
import com.jiunuan.live.core.server.common.ImMsg;
import com.jiunuan.live.core.server.service.IMsgAckCheckService;
import com.jiunuan.live.core.server.service.IRouterHandlerService;
import com.jiunuan.live.im.constants.ImMsgCodeEnum;
import com.jiunuan.live.im.dto.ImMsgBody;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Author: JiuNuan
 * @CreateTime: 2024-08-16 16:39
 * @Description:
 */
@Service
public class RouterHandlerServiceImpl implements IRouterHandlerService {
    @Resource
    private IMsgAckCheckService msgAckCheckService;
    /**
     * 接收消息
     *
     * @param imMsgBody
     */
    @Override
    public void onReceive(ImMsgBody imMsgBody) {
        if(sendMsgToClient(imMsgBody)) {
            // 当im服务推送消息至客户端，需要记录客户端的ack消息
            msgAckCheckService.recordMsgAck(imMsgBody,1);
            // 发送延迟消息
            msgAckCheckService.sendDelayMsg(imMsgBody);
        }
    }

    /**
     * 发送消息给客户端
     *
     * @param imMsgBody
     */
    @Override
    public boolean sendMsgToClient(ImMsgBody imMsgBody) {
        // 需要进行消息通知的userId
        Long userId = imMsgBody.getUserId();
        ChannelHandlerContext ctx = ChannelHandlerContextCache.get(userId);
        // 设置的时间为2倍心跳间隔，可能到sendMsgToClient方法时就消失，故需要判断是否存在
        if (ctx != null) {
            String msgId = UUID.randomUUID().toString();
            imMsgBody.setMsgId(msgId);
            ImMsg respMsg = ImMsg.build(ImMsgCodeEnum.IM_BIZ_MSG.getCode(), JSON.toJSONString(imMsgBody));
            ctx.writeAndFlush(respMsg);
            return true;
        }
        return false;
    }
}
